/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.cspimp.em.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.cspimp.em.domain.Plan;
import me.zhengjie.modules.cspimp.em.domain.vo.PlanVo;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.em.repository.PlanRepository;
import me.zhengjie.modules.cspimp.em.service.PlanService;
import me.zhengjie.modules.cspimp.em.service.dto.PlanDto;
import me.zhengjie.modules.cspimp.em.service.dto.PlanQueryCriteria;
import me.zhengjie.modules.cspimp.em.service.mapstruct.PlanMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://docs.auauz.net
* @description 服务实现
* @author zmm
* @date 2020-05-24
**/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class PlanServiceImpl implements PlanService {

    private final PlanRepository planRepository;
    private final PlanMapper planMapper;

    @Override
    public Map<String,Object> queryAll(PlanQueryCriteria criteria, Pageable pageable){
        Page<Plan> page = planRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(planMapper::toDto));
    }

    @Override
    public List<PlanDto> queryAll(PlanQueryCriteria criteria){
        return planMapper.toDto(planRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public PlanDto findById(Long id) {
        Plan plan = planRepository.findById(id).orElseGet(Plan::new);
        ValidationUtil.isNull(plan.getId(),"Plan","id",id);
        return planMapper.toDto(plan);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PlanDto create(PlanVo resources) {
        if (planRepository.findByName(resources.getName()) != null) {
            throw new EntityExistException(Plan.class, "name", resources.getName());
        }
        Plan plan = new Plan();
//        plan.setBid(SnowflakeIdWorker.getId());
        plan.setCid(0l);
//        plan.setStatus(1);
        plan.setAuditName(resources.getAuditName());
        plan.setFilePath(resources.getFilePath());
        plan.setName(resources.getName());
        plan.setPlanDetail(resources.getPlanDetail());
        plan.setPlanIntro(resources.getPlanIntro());
//        Date auditDate = null;
//        try {
//            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//            auditDate = sf.parse(resources.getAuditDate());
//        } catch (Exception e) {
//
//        }
        String auditDate=resources.getAuditDate();
        if(StringUtils.isBlank(auditDate)){
            throw new BadRequestException("审核日期不能为空");
        }
        plan.setAuditDate(auditDate);
        return planMapper.toDto(planRepository.save(plan));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PlanVo resources) {
        Plan plan = planRepository.findById(resources.getId()).get();
        ValidationUtil.isNull(plan.getId(), "Plan", "id", resources.getId());

        Plan p = planRepository.findByName(resources.getName());

        if (p != null && !p.getId().equals(plan.getId())) {
            throw new EntityExistException(Plan.class, "name", resources.getName());
        }
        plan.setAuditName(resources.getAuditName());
        plan.setFilePath(resources.getFilePath());
        plan.setName(resources.getName());
        plan.setPlanDetail(resources.getPlanDetail());
        plan.setPlanIntro(resources.getPlanIntro());
//        Date auditDate = null;
//        try {
//            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//            auditDate = sf.parse(resources.getAuditDate());
//        } catch (Exception e) {
//
//        }
        String auditDate=resources.getAuditDate();
        if(StringUtils.isBlank(auditDate)){
            throw new BadRequestException("审核日期不能为空");
        }        planRepository.save(plan);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            planRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<PlanDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PlanDto plan : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" cid",  plan.getCid());
            map.put("审核日期", plan.getAuditDate());
            map.put("文件地址", plan.getFilePath());
            map.put("应急预案名称", plan.getName());
            map.put("预案详情", plan.getPlanDetail());
            map.put("预案简介", plan.getPlanIntro());
            map.put("创建时间", plan.getCreateTime());
            map.put("更新时间", plan.getUpdateTime());
            map.put("审核人", plan.getAuditName());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}